﻿using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using EnvDTE;
using EnvDTE80;
using Microsoft.Practices.RecipeFramework;
using ProjectBase.Guidance.Helpers;

namespace ProjectBase.Guidance.Actions
{
    public class AddNugetImportAction : AddAssemblyVersionAction
    {
        public override void Execute()
        {
            InjectImportElement();
            ReferencePackagesConfigInWeb();
        }

        protected virtual void ReferencePackagesConfigInWeb()
        {
            var dte = GetService<DTE>(true);
            var dte2 = dte as DTE2;
            string source =
                Path.Combine(Path.GetDirectoryName(dte2.Solution.Properties.Item("Path").Value.ToString()), "Core");
            string target =
                Path.Combine(Path.GetDirectoryName(dte2.Solution.Properties.Item("Path").Value.ToString()), "Core");

            Trace.WriteLine("packages.config reference whould be added");
            FileInfo config =
                new DirectoryInfo(source).GetFiles("packages.config", SearchOption.AllDirectories).FirstOrDefault();

            if (config.Exists)
            {
                Trace.WriteLine("packages.config found at " + config.FullName);

                AppendLink(dte, config.FullName, ProjectType.Web, 2);

                dte2.Documents.CloseAll(vsSaveChanges.vsSaveChangesNo);
            }
        }
        protected virtual void InjectImportElement()
        {
            string source = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                         @"Templates\Solutions\Core");
            if (Directory.Exists(source))
            {
                var dte = GetService<DTE>(true);
                var dte2 = dte as DTE2;
                string target = Path.GetDirectoryName(dte2.Solution.Properties.Item("Path").Value.ToString());

                // iterate all projects to inject
                // <Import Project="$(SolutionDir)\.nuget\nuget.targets" />
                foreach (var projFile in Directory.GetFiles(target, "*.csproj", SearchOption.AllDirectories))
                {
                    // the project as Project
                    var file = new FileInfo(projFile);
                    var projectName = file.Name.Replace(".csproj", string.Empty);
                    Project prj = SolutionHelper.FindProjectByName(dte, projectName);
                    prj.Save();

                    // the project as XDocument
                    var project = XDocument.Load(projFile);

                    // Append: <Import Project="$(SolutionDir)\.nuget\nuget.targets" />
                    XNamespace xmlns = project.Root.Attribute("xmlns").Value;
                    var importElement = new XElement(xmlns + "Import");
                    var importAttribute = new XAttribute("Project", @"$(SolutionDir)\.nuget\nuget.targets");
                    importElement.Add(importAttribute);
                    project.Root.Add(importElement);

                    // save
                    project.Save(projFile);


                    // activate project, Reload it
                    dte.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer).Activate();

                    var solutionName = dte.Solution.Properties.Item("Name").Value.ToString();
                    var solutionFolder = prj.ParentProjectItem.ContainingProject.Name;
                    var path = solutionName + @"\" + solutionFolder + @"\" + prj.Name;

                    var item = dte2.ToolWindows.SolutionExplorer.GetItem(path);
                    item.Select(vsUISelectionType.vsUISelectionTypeSelect);

                    dte.ExecuteCommand("Project.UnloadProject");
                    dte.ExecuteCommand("Project.ReloadProject");
                }
            }
        }

        protected virtual void AppendLink(DTE dte, string dest, ProjectType pType, int buildAction = 1)
        {
            Project prj = SolutionHelper.FindProject(dte, pType);
            ProjectItem pi = prj.ProjectItems.AddFromFile(dest);
            pi.Properties.Item("BuildAction").Value = buildAction;

            Trace.WriteLine("AssemblyVersion added to: " + prj.Name);
        }

    }
}